package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;


@RestController
@RequestMapping("/admin/dish")
@Slf4j
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("")
    public Result saveDish(@RequestBody DishDTO dishDTO) {
        dishService.saveDish(dishDTO);
        //同步缓存
        redisTemplate.delete("dish_"+dishDTO.getCategoryId());
        return Result.success();
    }

    @GetMapping("/page")
    public Result<PageResult> page(DishPageQueryDTO dishPageQueryDTO){
        PageResult p = dishService.pageSelect(dishPageQueryDTO);
        return Result.success(p);

    }

    @DeleteMapping("")
    public Result delete(@RequestParam List<Long> ids){
        dishService.deleteDish(ids);
        //缓存全部删除
        //Set keys = redisTemplate.keys();
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result<DishVO> selectDishById(@PathVariable Long id){
        log.info("查询菜品id:{}",id);
        DishVO dishVO =  dishService.selectDishById(id);
        return Result.success(dishVO);
    }

    @PutMapping("")
    public Result updateDish(@RequestBody DishDTO dishDTO){
        dishService.update(dishDTO);
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return Result.success();
    }

    //根据分类 返回菜品
    @GetMapping("/list")
    public Result<List<Dish>> getListByCategoryId(Long categoryId){
        List<Dish> list = dishService.getListByCategoryId(categoryId);
        return Result.success(list);
    }
}
